<template>
  <!-- 递归遍历 -->
  <div class="recursion-goodsList">
    <div
      class="goods-box"
      v-for="goods in tempGoodsArr"
      :key="goods.mealType.mealTypeId"
    >
      <!-- 每一层级的标题, 根据层级paddingLeft会不同用来显示层级的关系 -->
      <div
        class="title"
        :style="{
          paddingLeft: `${level * 10 + 16}px`,
          color: colorList_title[level],
          fontWeight: level === 0 ? '700' : '400',
          fontSize: `${fontSize_title[level]}px`,
        }"
      >
        {{ goods.mealType.mealType }}
        <!-- <div
          class="line"
          :style="{ backgroundColor: colorList_title[level] }"
        ></div> -->
      </div>
      <!-- 只有mealList的时候才会渲染商品列表 -->
      <div class="goods-list" v-if="goods.mealList.length > 0">
        <van-swipe-cell>
          <van-card
            class="goods-card"
            @click="activeGoodsHandle(item)"
            v-for="item in goods.mealList"
            :key="item.mealId"
            :price="`${item.mealPrice}/份`"
            :title="item.mealName"
            :thumb="item.mealPictures[0]"
          >
            <template #tags>
              <van-tag plain type="danger" color="#a9a9a9"
                >销量{{ item.mealSales }}</van-tag
              >
            </template>
            <template #footer>
              <div class="btn-box">
                <div
                  @click.stop="
                    updateBuyCount(item, false, goods.mealType.mealType)
                  "
                  class="subtrat-btn"
                  v-show="item.buyCount !== 0"
                >
                  -
                </div>
                <div class="buy-count" v-show="item.buyCount !== 0">
                  {{ item.buyCount }}
                </div>
                <div
                  @click.stop="
                    updateBuyCount(item, true, goods.mealType.mealType)
                  "
                  class="add-btn"
                >
                  +
                </div>
              </div>
            </template>
          </van-card>
        </van-swipe-cell>
      </div>
      <!-- 如果还存在childType说明还有下一层级 -->
      <div class="next-box" v-if="goods.childType.length > 0">
        <Self :goodsArr="goods.childType" :level="level + 1" />
      </div>
    </div>

    <!-- 显示遮罩层 -->
    <van-overlay :show="show" z-index="9999">
      <div class="wrapper" v-if="show">
        <div class="wrapper-top">
          <h4>{{ isActiveGoods.mealName }}</h4>
          <div class="block">
            <van-image
              class="van-image"
              width="10rem"
              height="10rem"
              fit="contain"
              :src="isActiveGoods.mealPictures[0]"
            />
            <h5>销量{{ isActiveGoods.mealSales }} | 好评率100%</h5>
            <van-icon size="30" name="close" @click="show = false" />
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
const Self = () => import("@/components/home/recursion-goods.vue");
// import Self from "@/components/home/recursion-goods.vue"; // 这样会报错, 只能是上面的异步加载方法
export default {
  name: "recursion-goodsList",
  props: {
    goodsArr: {
      type: Array,
      default: [],
    },
    level: {
      type: Number, // 递归的层级
      default: 0,
    },
  },
  data() {
    return {
      show: false,
      // tempGoodsArr: [],
      colorList_title: ["#1e1e1e", "#e47105", "#616161"],
      fontSize_title: ["14", "12"],
      isActiveGoods: {},
    };
  },
  components: {
    Self,
  },
  methods: {
    ...mapMutations("m_user", ["setBillList"]),
    activeGoodsHandle(goods) {
      this.show = true;
      this.isActiveGoods = goods;
    },
    updateBuyCount(goods, isAdd, mealType) {
      goods.mealType = mealType;
      // let tempBillList = this.deepClone(this.billList); // 这里不需要深拷贝, 不然的话下面的indexOf会找不到
      let tempBillList = this.billList;
      let CurIndex = -1; // 默认是-1 未找到
      tempBillList.some((ele, index) => {
        if (ele.mealId === goods.mealId) {
          CurIndex = index;
          return true;
        }
      });
      // let index = tempBillList.indexOf(goods);
      if (~CurIndex) {
        // 如果未找到就不需要删除, 如果是更新就删除掉原来的
        tempBillList.splice(CurIndex, 1);
      } else {
        // index 为 -1的时候让它为0, 到时候添加的时候往最前面添加
        CurIndex = 0;
      }

      let flag = true; // 控制是否添加的变量
      if (isAdd) {
        goods.buyCount++;
      } else {
        goods.buyCount--;
        if (goods.buyCount <= 0) {
          goods.buyCount = 0;
          flag = false; // 删除就行不需要添加
        }
      }

      if (flag) {
        // 在原来的位置添加最新的
        tempBillList.splice(CurIndex, 0, goods);
      }

      this.setBillList(tempBillList);
      // jwt加密后存入localStorage中, 防止恶意篡改localStorage数据, jwt加密必须是对象形式
      let tempBill = this.$jwt.sign(
        { bill: tempBillList },
        this.$appConfig.jwt_secret,
        {
          expiresIn: "1day",
        }
      );
      localStorage.setItem("shopCar", tempBill);

      if (tempBillList.length <= 0) {
        localStorage.removeItem("shopCar");
      }
    },
    // 深拷贝origin引用类型并返回
    deepClone(origin) {
      return JSON.parse(JSON.stringify(origin));
    },
  },
  computed: {
    ...mapState("m_user", ["billList"]),
    tempGoodsArr() {
      let temp = this.goodsArr.map((item) => {
        item.mealList.forEach((goods) => {
          if(!goods.buyCount) {
            let temp = this.billList.find((ele) => {
              return goods.mealId === ele.mealId;
            });
            this.$set(goods, "buyCount", temp ? temp.buyCount : 0);
          }

          if(!goods.changedPrice) {
            // 如果已经转换过价格就不需要转换了, 如果没有转换过就进行转换并添加这个标志属性
            goods.mealPrice = goods.mealPrice / 100; // 后端传过来的单位是分, 100分钱 = 1块钱
            this.$set(goods, "changedPrice", true);
          }
        });
        return item;
      })

      return temp;
    }
  },
};
</script>

<style lang="scss" scoped>
.title {
  background-color: #fff;
  color: #000;
  font-size: 14px;
  padding-top: 5px;
  // .line {
  //   width: 10%;
  //   height: 1px;
  //   background-color: #ccc;
  // }
}

.btn-box {
  display: flex;
  justify-content: flex-end;
}
div[class$="-btn"] {
  display: flex;
  justify-content: center;
  align-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: rgb(30, 189, 252);
  font-size: 18px;
  color: #fff;
  box-sizing: border-box;
}
div.subtrat-btn {
  background-color: #fff;
  border: 1px solid #ccc;
  color: #ccc;
  line-height: 16px;
}

.buy-count {
  line-height: 20px;
  margin: 0 5px;
}

.goods-card {
  background-color: #fff !important;
}

/* 遮罩层 */
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.wrapper-top {
  width: 200px;
  height: 210px;
  background-color: white;
  position: relative;
}

.block {
  position: absolute;
  left: 20px;
}
.block > i {
  color: #fff;
  margin: 20px 0 30px 65px;
}

.wrapper-top > h4 {
  font-size: 15px;
  color: #000;
}
.block > h5 {
  color: gray;
  font-size: 8px;
  padding-top: 2px;
  font-weight: 100;
}

.van-card:not(:first-child) {
  margin: 0 !important;
}
</style>
